package cn.liulin.java8.stream;

import cn.liulin.java8.pojo.Dish;
import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * cn.liulin.java8.stream$
 *
 * @author ll
 * @date 2021-10-15 14:54:33
 **/
public class CollectStream {
    public static void main(String[] args) {
        Dish dish1 = new Dish("hasd", 100);
        Dish dish2 = new Dish("g", 200);
        Dish dish3 = new Dish("asdf", 300);
        Dish dish4 = new Dish("dfg", 400);
        List<Dish> menu = Arrays.asList(dish1, dish2, dish3, dish4);
//        collectOne(menu);
//        collectTwo(menu);
//        collectThree(menu);
//        collectFour(menu);
//        collectFive(menu);
        collectSix(menu);
    }

    private static void collectSix(List<Dish> menu) {
        Integer collect = menu.stream().collect(Collectors.reducing(0, //初始值
                Dish::getCalories, //转换函数
                Integer::sum));//累计函数
        System.out.println(collect);
    }

    private static void collectFive(List<Dish> menu) {
        Optional<Dish> collect = menu.stream()
                .collect(Collectors.reducing((d1, d2) -> d1.getCalories() > d2.getCalories() ? d1 : d2));
        System.out.println(collect.get());
    }

    private static void collectFour(List<Dish> menu) {
        Integer collect = menu.stream()
                .collect(Collectors.reducing(0, Dish::getCalories, (i, j) -> i + j));
        System.out.println(collect);
    }

    private static void collectThree(List<Dish> menu) {
        List<String> collect = menu.stream()
                .map(d -> d.getName().split(""))
                //流的扁平化处理，将流中的值再次变成流，并插在一起，相当于双重for循环，取值处理
                .flatMap(d -> Arrays.stream(d))
                .distinct()
                .collect(Collectors.toList());
        System.out.println(collect);

    }

    private static void collectTwo(List<Dish> menu) {
        String collect = menu.stream()
                .map(Dish::getName)
                .collect(Collectors.joining());
        System.out.println(collect);
    }

    /**
     * summarizingInt通用类型
     * @author ll
     * @date 2021-10-15 14:56:47
     * @param menu
     * @return void
     **/
    private static void collectOne(List<Dish> menu) {
        IntSummaryStatistics collect = menu.stream()
                .collect(Collectors.summarizingInt(Dish::getCalories));
        System.out.println(JSON.toJSONString(collect));
    }
}
